import re
from django.shortcuts import HttpResponse,redirect
from django.utils.deprecation import MiddlewareMixin

class PermissoinCore(MiddlewareMixin):

    def process_request(self,request):
        # print("permission_list" ,request.session.get("permission_list"))

        current_path = request.path

        # 设置白名单
        for reg in ["/login/","/admin/*","/index/"]:
            ret = re.search(reg,current_path)
            if ret:
                return None  # 放行

        # 校验是否登录
        user_id = request.session.get("user_id")
        if not user_id:  # session中找不到登录的id信息
            return redirect("/login/")


        # 校验访问的权限

        permission_list = request.session.get("permission_list")

        for reg in permission_list:
            reg = f"^{reg}$"
            ret = re.search(reg,current_path)
            if ret:
                return None

        return HttpResponse("无访问权限!")
